package com.bnz.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {

    //1. 得到getSqlSessionFactory对象
    private static SqlSessionFactory getSqlSessionFactory() throws IOException {
        //1.1 定义要读取的全局配置文件
        String resource = "mybatis/mybatis-config.xml";
        //1.2 得到配置文件相关的输入流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //1.3 根据输入流得到相关的sqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //1.4 返回
        return sqlSessionFactory;
    }

    //2. 得到sqlSession对象
    public static SqlSession getSqlSession(){
        try {
            return getSqlSessionFactory().openSession(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
